var express = require('express');
var app = new express();
var mongoose = require('mongoose');
var cors = require('cors');
app.use(cors());

mongoose.connect("mongodb://localhost:27017/person",{useNewUrlParser:true},function(err){
  if(err){
    console.log('数据库链接未遂');
  }else{
    console.log('数据库链接成功');
  }
});
var personSchema = new mongoose.Schema({
  name:{type:String},
  age:{type:Number,default:0}
},{ collection: 'aa' });

// 创建一个Model：是由schema构造生成器生成的一个model
var Model = mongoose.model('aa',personSchema);
/************************************************/

//获取所有数据
app.get('/all',function (req,res) {
  Model.find({},function (err,doc) {
    if (err){
      console.error('查询出错');
    } else{
      console.log(doc);
      res.send(doc);
    }
  })
})

//用户提交
app.get('/tijiao',function (req,res) {
  var name = req.query.name;
  var age = req.query.age;
  Model.create({name:name,age:age},function (err) {
    if (err){
      res.send({code:0});
    } else {
      res.send({code:1});
    }
  })
});
//更新

app.get('/update',function (req,res) {
  var name = req.query.name;
  var age = req.query.age;
  var id = req.query.id;
  Model.updateOne({_id:id},{$set:{name:name,age:age}},function (err) {
    if (err){
      res.send({code:0});
    } else{
      res.send({code:1});
    }
  })
});
//删除
app.get('/del',function (req,res) {
  Model.deleteOne({_id:req.query.id},function (err) {
    if (err){
      res.send({code:0});
    } else{
      res.send({code:1});
    }
  })
});



app.listen(8081);
console.log('服务器启动成功');
